package com.hup.htts.view.setting;

import com.hup.htts.model.MainConfig;
import com.hup.utils.commons.start.DialogHelper;
import com.hup.utils.commons.start.LookThemeUtil;
import com.hup.utils.commons.start.SpringContext;
import com.hup.utils.commons.start.StartupInfo;
import com.hup.utils.commons.start.VersionConfig;
import com.hup.utils.swing.frame.BaseFrame;
import lombok.extern.log4j.Log4j2;

import java.awt.event.WindowEvent;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 设置窗口
 *
 * @author hugan
 * @date 2021/12/14
 */
@Log4j2
public class SettingDialog extends BaseFrame {

    private final MainConfig config;
    private SettingForm form;

    public SettingDialog() {
        super(StartupInfo.getApplicationChName());
        config = SpringContext.getBean(MainConfig.class);
        setSubTitle("设置");
        initView();
        initListener();
    }

    private void initListener() {
        form.keySpeak.setKeyChangedListener(() -> {
            form.btnSave.setEnabled(true);
        });
        form.keyStop.setKeyChangedListener(() -> {
            form.btnSave.setEnabled(true);
        });
        form.btnSave.addActionListener(e -> {
            config.setHotKey(MainConfig.HK_SPEAK, form.keySpeak.getLstKeyCode());
            config.setHotKey(MainConfig.HK_STOP, form.keyStop.getLstKeyCode());
            config.save();
            form.btnSave.setEnabled(false);
            //GlobalKeyService会自动更新
        });
        form.btnCancel.addActionListener(e -> {
            if (onWindowClosing(null)) dispose();
        });
    }

    private void initView() {
        form = new SettingForm();
        setContentPane(form.root);

        VersionConfig versionConfig = SpringContext.getBean(VersionConfig.class);
        form.labVersion.setText(versionConfig.version);
        form.labVersion.setToolTipText(versionConfig.buildTime);
        form.keySpeak.setKeyCode(config.getMapHotKey(MainConfig.HK_SPEAK), false);
        form.keyStop.setKeyCode(config.getMapHotKey(MainConfig.HK_STOP), false);
        form.btnSave.setEnabled(false);

        LookThemeUtil.initFrameSize(this, 500, 400);
        setLocationRelativeTo(null);
    }

    @Override
    public boolean onWindowClosing(WindowEvent e) {
        if (form.btnSave.isEnabled()) {
            AtomicBoolean res = new AtomicBoolean(false);
            DialogHelper.yesNo("确认[不保存修改]?").okAction(() -> res.set(true)).show(this);
            return res.get();
        }
        return true;
    }

    @Override
    public void onShown() {
        form.btnCancel.requestFocus();
    }

}
